package com.simen.multiprocess.communication;

import android.app.ActivityManager;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Debug;
import android.os.MemoryFile;
import android.view.View;
import android.widget.ListView;

import com.simen.absadapter.AbsAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            MemoryFile file = new MemoryFile("this", 1000);

            ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.getMemoryInfo(memoryInfo);

            Debug.MemoryInfo memoryInfo1 = new Debug.MemoryInfo();
            Debug.getMemoryInfo(memoryInfo1);

        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Data> lists = new ArrayList<>();

        PackageManager pkm = getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory("android.intent.category.SAMPLE_CODE");
        List<ResolveInfo> resolveInfos = pkm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        for (int index = 0; resolveInfos != null && index < resolveInfos.size(); index++) {
            ResolveInfo info = resolveInfos.get(index);
            if (!getPackageName().equals(info.activityInfo.packageName)) {
                continue;
            }

            Data data = new Data();
            data.name = getString(info.activityInfo.labelRes);
            data.pkn = info.activityInfo.packageName;
            data.classType = info.activityInfo.name;
            lists.add(data);
        }

        setListAdapter(new AbsAdapter<Data>(this, lists, android.R.layout.simple_list_item_1) {
            @Override
            protected boolean onItemAdapter(AbsViewHolder viewHolder, Data element, int position) {
                viewHolder.setTextOrButton(android.R.id.text1, element.name);
                return false;
            }
        });

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Data data = (Data) v.getTag(R.id.absadapter_id);

        Intent intent = new Intent();
        intent.setClassName(data.pkn, data.classType);
        startActivity(intent);
    }

    class Data {
        String name;
        String classType;
        String pkn;
    }

}